<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2018/6/7
 * Time: 1:51
 */

namespace app\api\controller\v2;

use app\common\cachemodel\FortuneSetting;
use app\common\lib\exception\ApiException;
use app\common\model\FortuneCache;
use app\common\model\FortuneNote;
use app\common\model\Recode;
use Exception;
use think\Log;
use think\response\Json;

/**
 * 每日运势相关接口
 */
class Fortune extends Auth
{
    /**
     * 每日运势详情
     * @return Json
     * @throws ApiException
     * @throws Exception
     */
    public function index()
    {
        if (!request()->isGet())
        {
            return show(config('code.error'), '未知操作', [], 403);
        }
        $rid = input('get.rid/d');
        // 当前时间
        $time = strtotime(date('Y-m-d', input('get.time/d')));

        if (!$rid) return show(config('code.error'), '档案信息获取失败');

        $recode = (new Recode())->getRecode(['id' => $rid]);
        if (!$recode || $recode['uid'] != $this->user['id'])
        {
            return show(config('code.error'), '档案不存在');
        }

        $uid = $this->user['id'];

        $arr = \app\common\cachemodel\FortuneCache::CheckFortuneSevenUnlockStatus($uid, $rid, $time);

        $is_unlock = $arr['is_unlock'];
        $seven = $arr['time'];//日记标识
//        $seven = $arr['seven'];//日记标识
        $fortune = $arr['fortune'];//解锁标识
        $selfId = $arr['selfId'];
        $note_status = $arr['note_status'];

        if ($is_unlock === true)
        {
            $dailyFortune = new \app\everyday\controller\Index();

            /** @var int 当天中午12点的时间戳 $time */
            $data = $dailyFortune->init($rid, $time + 3600 * 12);
            // 获取需要显示的运势分类
            $icon = (new FortuneSetting())->FortuneSetting($this->user['id']);

            $name = explode(',', $icon['name']);

            $fortune_list = [];

            foreach ($name as $k => $v)
            {
                foreach (config('fortune.set') as $kk => $vv)
                {
                    if ($k == $kk && $v == 1)
                    {
                        // 过滤不需要显示的
                        $fortune_list[] = $data['fortune_list'][$k];
                    }
                }
            }

            $data['fortune_list'] = $fortune_list;
        }

        // 去重
        $seven = array_unique($seven);
        // 重新索引
        $data['time'] = array_values($seven);

        // 去重
        $fortune = array_unique($fortune);
        // 重新索引
        $data['fortune'] = array_values($fortune);
        $data['self_rid'] = $selfId['id'];
        $data['note_status'] = $note_status;

        return show(200, '加载成功', $data);
    }

    /**
     * 根据年月获取日记标识
     * @return Json
     * @throws ApiException
     */
    public function note_time()
    {
        if (!request()->isGet())
        {
            return show(config('code.error'), '未知操作', [], 403);
        }

        // 当前查看的具体日期
        $time = strtotime(date('Y-m', input('get.time')) . '-01');

        $rid = input('get.rid/d');

        $recode = (new Recode())->getRecode(['id' => $rid]);
        if (!$recode || $recode['uid'] != $this->user['id'])
        {
            return show(config('code.error'), '档案不存在');
        }

        $uid = $this->user['id'];

        $arr = (new FortuneCache())->getFortuneCalendar($rid, $time, $uid);


        return show(200, '成功', $arr);
    }

    /**
     * 获取运势图标设置
     * @return Json
     * @throws Exception
     */
    public function chart_list()
    {
        if (!request()->isGet())
        {
            return show(config('code.error'), '未知操作', [], 403);
        }

        $arr = (new FortuneSetting())->FortuneSetting($this->user['id']);

        $name = explode(',', $arr['name']);

        $data = [];
        foreach ($name as $k => $v)
        {
            foreach (config('fortune')['set'] as $kk => $vv)
            {
                if ($k == $kk)
                {
                    $data[] = [
                        'id' => $k,
                        'name' => $vv,
                        'status' => $v
                    ];
                }
            }
        }

        return show(200, '提交成功', $data);
    }

    /**
     * 更新运势图标设置
     * @return Json
     * @throws Exception
     */
    public function chart_save()
    {
        if (!request()->isPut())
        {
            return show(config('code.error'), '未知操作', [], 403);
        }
        $ids = explode(',', input('param.ids/s'));

        if (count($ids) !== 5)
        {
            return show(config('code.error'), '必须显示5项');
        }
        $name = config('fortune.set');

        $FortuneSetting = new FortuneSetting();

        $data = $FortuneSetting->FortuneSetting($this->user['id']);

        foreach ($name as $k => $v)
        {
            if (in_array($k, $ids)) $name[$k] = 1;

            else $name[$k] = 0;
        }
        if ($data)
        {
            $arr = [
                'name' => implode(',', $name),
            ];
            $FortuneSetting->UpdateData($this->user['id'], $arr);
        } else
        {
            $arr = [
                'name' => implode(',', $name),
                'uid' => $this->user['id']
            ];
            $FortuneSetting->SaveData($this->user['id'], $arr);
        }
        return show(200, '更新成功', []);

    }

    /**
     * 运势日记列表
     * @return Json
     * @throws Exception
     */
    public function note()
    {
        if (!request()->isGet())
        {
            return show(config('code.error'), '未知操作', [], 403);
        }
        $page = input('get.page/d', 1);
        $uid = $this->user['id'];
        $map = ['uid' => $uid, 'isself' => 1];

        $RecodeModel = new  Recode();
        $FortuneNoteModel = new FortuneNote();

        $recode_info = $RecodeModel->getSelfRecode($map);

        $map['rid'] = $recode_info['id'];
        $map['page'] = $page;
        try
        {
            $data = $FortuneNoteModel->getListPage($map);
        }
        catch (\Exception $e)
        {
            Log::write('获取运势日记信息失败' . $e->getMessage() . var_export(request()->param(), true), 'error', true);
            $data = [
                'total' => 0,
                'per_page' => 10,
                'current_page' => $page,
                'last_page' => 1,
                'data' => []
            ];
        }

        if (isset($data['data']) && !empty($data['data']))
        {
            $array = [];
            foreach ($data['data'] as $k => $v)
            {
                $array[] = [
                    'id' => (int)$v['id'],
                    'create_time' => $v['create_time'],
                    'content' => $v['content'],
                    'state' => (int)$v['state'],
                    'mood' => (int)$v['mood'],
                    'from' => [
                        'rid' => (int)$v['rid'],
                        'time' => $v['time'],
                        'remark' => '每日运势',
                        'icon_url' => config('fortune.thumb'),
                    ],
                ];
            }
            $data['data'] = $array;
            return show(200, '列表加载成功', $data);
        }
        return show(200, '还没有运势日记，您可以为每日运势打分哦~', $data);
    }

    /**
     * 新建日记
     * @return Json
     * @throws Exception
     */
    public function save()
    {
        if (!request()->isPost())
        {
            return show(config('code.error'), '未知操作', [], 403);
        }
        $content = htmlspecialchars(input('post.content'));
        $time = strtotime(date('Y-m-d', input('post.time/d')));
        $state = input('post.state/d');
        $mood = input('post.mood/d');
        $from = input('post.from/d');
        $uid = $this->user['id'];
        $now_time = time();

        $RecodeModel = new Recode();
        //        获取档案id
        $rid = $RecodeModel->getSelfRecode(['uid' => $uid]);

//        $arr = (new \app\common\model\Fortune())->getUserUnlockFortune(['uid' => $uid, 'time' => $time, 'rid' => $rid['id']]);

        $arr = \app\common\cachemodel\FortuneCache::CheckFortuneSevenUnlockStatus($uid, $rid['id'], $time);
        $is_unlock = $arr['is_unlock'];

        if ($is_unlock)
        {
            $FortuneNoteModel = new FortuneNote();
            $array = $FortuneNoteModel->saveFortuneNote(['rid' => $rid['id'], 'uid' => $uid, 'content' => $content, 'from' => $from, 'state' => $state, 'mood' => $mood, 'time' => $time, 'create_time' => $now_time]);
            if ($array === false)
            {
                return show(config('code.error'), $FortuneNoteModel->getError());
            }


        } else
        {
            return show(config('code.error'), '您需要解锁当天后,才可添加日记');
        }

        return show(config('code.success'), 'Success');
    }

    /**
     * 编辑日记
     * @return Json
     * @throws Exception
     */
    public function update()
    {
        if (!request()->isPut())
        {
            return show(config('code.error'), '未知操作', [], 403);
        }
        $id = input('param.id/d');
        $content = htmlspecialchars(input('param.content'));
        $state = input('param.state/d');
        $mood = input('param.mood/d');

        $FortuneNoteModel = new FortuneNote();
        //        获取档案id
        $data = [
            'content' => $content,
            'state' => $state,
            'mood' => $mood,
        ];
        if (trim($content) == '')
        {
            return show(config('code.error'), '内容不能为空');
        }

        $array = $FortuneNoteModel->UpdateData($id, $data);

        return show(200, '修改成功', $array);


    }

    /**
     * 删除日记
     * @return Json
     * @throws Exception
     */
    public function del()
    {
        if (!request()->isDelete())
        {
            return show(config('code.error'), '未知操作', [], 403);
        }
        $id = input('param.id/d');

        $FortuneNoteModel = new FortuneNote();

        $FortuneNoteModel->DelData($id, $this->user['id']);
        return show(200, '删除成功');
    }

    /**
     * 选择开通方式
     * @return Json
     */
    public function unlock_type()
    {
        if (!request()->isGet())
        {
            return show(config('code.error'), '未知操作', [], 403);
        }
        $FortuneGoods = new FortuneCache();
        $data = $FortuneGoods->getFortuneGoods($this->is_apple_pay, $this->apple_goods);

        $array = [];
        foreach ($data['fortune_day']['goods_data'] as $goods_datum)
        {
            $array[] = [
                'gid' => $goods_datum['gid'],
                'name' => $goods_datum['name'],
                'price' => $goods_datum['now_price']
            ];
        }

        return show(config('code.success'), '获取成功', $array);

    }

    protected $restActionList = ['index', 'read', 'save', 'update', 'delete'];
}
